<!--
  Copyright (c) 2024 Intel Corporation

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<script lang="ts">
	import { Drawer, Button, CloseButton, Tabs, TabItem } from "flowbite-svelte";
	import { InfoCircleSolid } from "flowbite-svelte-icons";
	import { sineIn } from "svelte/easing";
	import UploadFile from "./upload-knowledge.svelte";
	import PasteURL from "./PasteKnowledge.svelte";
	import {
		knowledge1,
		knowledgeName,
		storageFiles,
	} from "$lib/shared/stores/common/Store";
	import { getNotificationsContext } from "svelte-notifications";
	import {
		fetchAllFile,
		fetchKnowledgeBaseId,
		fetchKnowledgeBaseIdByPaste,
	} from "$lib/network/upload/Network";
	import DocCard from "../doc_management/docCard.svelte";
	import NoFile from "$lib/assets/upload/no-file.svelte";
	import LoadingButton from "$lib/assets/upload/loading-button.svelte";

	const { addNotification } = getNotificationsContext();

	$: files = $storageFiles ? $storageFiles : [];
	// $: files = $storageFiles.filter((file) => file.isUserUploaded === true);

	let hidden6 = true;
	let uploading = false;

	let transitionParamsRight = {
		x: 320,
		duration: 200,
		easing: sineIn,
	};

	async function handleKnowledgePaste(
		e: CustomEvent<{ pasteUrlList: string[] }>
	) {
		uploading = true;
		try {
			const pasteUrlList = e.detail.pasteUrlList;
			const res = await fetchKnowledgeBaseIdByPaste(pasteUrlList);
			handleUploadResult(res, "knowledge_base");
		} catch {
			handleUploadError();
		}
	}

	async function handleKnowledgeUpload(e: CustomEvent<any>) {
		uploading = true;
		try {
			// 这里依然对单个文件进行处理
			const blob = await fetch(e.detail.src).then((r) => r.blob());
			const fileName = e.detail.fileName;
			const res = await fetchKnowledgeBaseId(blob, fileName);
			handleUploadResult(res, fileName);
		} catch {
			handleUploadError();
		}
	}

	async function handleUploadResult(res: Response, fileName: string) {
		if (res.status === 200) {
			knowledge1.set({ id: "default" });
			knowledgeName.set(fileName);
			showNotification("Uploaded successfully", "success");
			// update fileStructure
			const res = await fetchAllFile();
			uploading = false;
			console.log("handleUploadResult", res);

			if (res) {
				const userUploadedFiles = res.map((file) => ({
					...file,
					isUserUploaded: true, // 标志为用户上传的文件
				}));
				storageFiles.set(userUploadedFiles);
				files = $storageFiles;
			}
		} else {
			//showNotification("Uploaded failed", "error");
		}
	}

	function handleUploadError() {
		//showNotification("Uploaded failed", "error");
	}

	function showNotification(text: string, type: string) {
		addNotification({
			text: text,
			position: "top-left",
			type: type,
			removeAfter: 3000,
		});
	}
</script>

<div class="text-center">
	<Button
		on:click={() => (hidden6 = false)}
		class="bg-transparent focus-within:ring-gray-300 hover:bg-transparent focus:ring-0"
		data-testid="open-upload"
	>
		<svg
			t="1738946856084"
			class="icon"
			viewBox="0 0 1024 1024"
			version="1.1"
			xmlns="http://www.w3.org/2000/svg"
			p-id="1968"
			width="30"
			height="30"
			><path
				d="M436.224 258.346667C427.562667 256.256 417.877333 256 384.512 256H332.8c-36.565333 0-61.397333 0-80.597333 1.621333-18.688 1.493333-28.288 4.266667-34.944 7.68a85.333333 85.333333 0 0 0-37.290667 37.290667c-3.413333 6.656-6.186667 16.213333-7.68 34.986667C170.666667 356.736 170.666667 381.525333 170.666667 418.133333v187.733334c0 36.565333 0 61.397333 1.621333 80.597333 1.493333 18.688 4.266667 28.288 7.68 34.944a85.333333 85.333333 0 0 0 37.290667 37.290667c6.656 3.413333 16.213333 6.186667 34.944 7.68C271.402667 768 296.234667 768 332.8 768h358.4c36.565333 0 61.397333 0 80.597333-1.621333 18.688-1.493333 28.288-4.266667 34.944-7.68a85.333333 85.333333 0 0 0 37.290667-37.290667c3.413333-6.656 6.186667-16.213333 7.68-34.944 1.578667-19.2 1.621333-44.032 1.621333-80.597333v-102.4c0-36.565333 0-61.397333-1.621333-80.597334-1.493333-18.688-4.266667-28.288-7.68-34.944a85.333333 85.333333 0 0 0-37.290667-37.290666c-6.656-3.413333-16.213333-6.186667-34.944-7.68C752.597333 341.333333 727.765333 341.333333 691.2 341.333333H554.666667a42.666667 42.666667 0 0 1-30.165334-12.501333l-25.344-25.344c-23.594667-23.552-30.634667-30.250667-38.272-34.901333a85.418667 85.418667 0 0 0-24.661333-10.24zM388.864 170.666667c27.093333 0 47.530667 0 67.285333 4.693333a170.666667 170.666667 0 0 1 49.322667 20.48c17.322667 10.581333 31.786667 25.088 50.944 44.245333l3.072 3.072 12.842667 12.842667h120.618666c34.346667 0 62.72 0 85.76 1.877333 24.021333 1.962667 46.08 6.186667 66.773334 16.725334a170.666667 170.666667 0 0 1 74.581333 74.581333c10.538667 20.693333 14.762667 42.752 16.725333 66.730667 1.877333 23.082667 1.877333 51.456 1.877334 85.76v105.941333c0 34.346667 0 62.72-1.877334 85.76-1.962667 24.021333-6.186667 46.08-16.725333 66.773333a170.666667 170.666667 0 0 1-74.581333 74.581334c-20.693333 10.538667-42.752 14.762667-66.730667 16.725333-23.082667 1.877333-51.456 1.877333-85.76 1.877333H331.008c-34.346667 0-62.72 0-85.76-1.877333-24.021333-1.962667-46.08-6.186667-66.773333-16.725333a170.666667 170.666667 0 0 1-74.581334-74.581334c-10.538667-20.693333-14.762667-42.752-16.725333-66.730666C85.333333 670.293333 85.333333 641.962667 85.333333 607.658667V416.341333c0-34.346667 0-62.72 1.877334-85.76 1.962667-24.021333 6.186667-46.08 16.725333-66.773333a170.666667 170.666667 0 0 1 74.581333-74.581333c20.693333-10.538667 42.752-14.762667 66.730667-16.725334C268.373333 170.666667 296.704 170.666667 331.008 170.666667h57.856z"
				fill="#2A343D"
				p-id="1969"
			/></svg
		>
	</Button>
</div>

<Drawer
	backdrop={false}
	placement="right"
	transitionType="fly"
	transitionParams={transitionParamsRight}
	bind:hidden={hidden6}
	class=" border-2 border-b-0 border-r-0 shadow"
	id="sidebar6"
>
	<div class="flex items-center">
		<h5
			id="drawer-label"
			class="mb-4 inline-flex items-center text-base font-semibold text-gray-500 dark:text-gray-400"
		>
			<InfoCircleSolid class="me-2.5 h-4 w-4" />Data Source
		</h5>
		<CloseButton
			on:click={() => (hidden6 = true)}
			class="mb-4 dark:text-white"
		/>
	</div>
	<p class="mb-6 text-sm text-gray-500 dark:text-gray-400">
		Please upload your local file or paste a remote file link, and Chat will
		respond based on the content of the uploaded file.
	</p>

	<Tabs
		style="full"
		defaultClass="flex rounded-lg divide-x rtl:divide-x-reverse divide-gray-200 shadow dark:divide-gray-700 focus:ring-0"
	>
		<TabItem class="w-full" open>
			<span slot="title">Upload File</span>
			<UploadFile on:upload={handleKnowledgeUpload} />
		</TabItem>
		<TabItem class="w-full" data-testid="exchange-paste">
			<span slot="title">Paste Link</span>
			<PasteURL on:paste={handleKnowledgePaste} />
		</TabItem>
	</Tabs>
	{#if uploading}
		<div class="my-6 flex flex-col items-center justify-center">
			<LoadingButton />
		</div>
	{/if}

	{#if files.length > 0}
		<DocCard {files} />
	{:else}
		<div class="mt-6 flex flex-col items-center justify-center">
			<NoFile />
			<p class=" text-sm opacity-70">No files uploaded</p>
		</div>
	{/if}
</Drawer>
